<template>
    <div class="address-edit">
        <van-nav-bar left-arrow title="编辑收货地址"
                     right-text="删除"
                     @click-left.stop="handleRouteBack"
                     @click-right.stop="handleDeleteAddress"/>
        <white-space/>
        <address-form :address="address" :loading="loading" @submit="handleSubmitSave"/>
    </div>

</template>

<script>
  import { customer, message, security } from "@mall/api-services"
  import AddressForm from "@/views/address/AddressForm"
  import { NavBar, Toast } from "vant"
  import WhiteSpace from "@/components/WhiteSpace"

  export default {
    name: "AddressNew",
    components: {
      AddressForm,
      WhiteSpace,
      [NavBar.name]: NavBar,
    },
    props: {
      id: String,
    },
    data() {
      return {
        loading: false,
        address: new customer.CustomerAddress(),
      }
    },
    created() {
      this.refreshAddress()
    },
    methods: {
      refreshAddress() {
        const { id } = this
        const customerId = security.SecurityUserHolder.getUserId()
        Toast.loading()
        customer.CustomerAddressServiceV1
          .getAddress(customerId, id)
          .then(address => this.address = address)
          .finally(() => Toast.clear())
      },
      handleRouteBack() {
        this.$router.back()
      },
      handleSubmitSave(values) {
        const customerId = security.SecurityUserHolder.getUserId()
        this.loading = true
        customer.CustomerAddressServiceV1
          .setAddress(customerId, values)
          .then(() => Toast.success("保存成功"))
          .then(() => this.$router.back())
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.loading = false)
      },
      handleDeleteAddress() {
        const customerId = security.SecurityUserHolder.getUserId()
        const { id } = this
        customer.CustomerAddressServiceV1
          .removeAddress(customerId, id)
          .then(() => Toast.success("删除成功"))
          .then(() => this.$router.back())
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
      },
    },
  }
</script>

<style lang="scss" scoped>
    .address-edit {

    }
</style>
